const express = require('express');
const router = express.Router();

const {
	DataRls,
	Message,
	Email
} = require("../config/class.js");
const {
	getEmailsById,
	addEmailToList,
	updateEmailRead,
	deleteEmailsByIdList
} = require("../db/emailsdb.js");
const {
	Socket
} = require('socket.io-client');

// 根据id获取所有邮件的方法
router.post('/getEmails', async function(req, res, next) {
	let rls;

	// 判断用户是否在线
	if (req.session.user) {
		// 如果在线，则使用用户本身的id，获取邮件
		rls = await getEmailsById(req.session.user.emailId);
	} else {
		rls = new DataRls(
			"邮件列表获取失败",
			[],
			false,
			new Error("用户未登录，无法获取邮件列表"),
		);
	}


	res.json(rls);
});


// 往指定路由中添加邮件的方法
router.post('/addEmail', async function(req, res, next) {
	let {
		id, //增加的用户id
		message, //增加的邮件
		result
	} = req.body;

	// 创建email对象
	let emailObj = new Email(message, Boolean(result));

	// 调用方法，增加邮件
	let rls = await addEmailToList(id, emailObj);

	res.json(rls);
});


// 更新用户邮件相关信息的方法
router.post('/updateEmail', async function(req, res, next) {
	try {
		let {
			deletList, //删除邮件列表
			readList //已读邮件列表
		} = req.body;


		// 更新已读列表
		let rls = await updateEmailRead(req.session.user.emailId, readList);

		// 删除邮件的方法
		if (deletList.length) {
			await deleteEmailsByIdList(req.session.user.emailId, deletList)
		}


		res.json(rls);
	} catch (error) {
		res.json(error);
	}
});


module.exports = router;